const config = require("../configs.js");

// 定义按钮配置映射（包含对应的处理函数模板）
const buttonConfigs = {
  add: {
    handlerTemplate: () => `
      /**
       * @description 新增
       * @returns {void}
       */
      const handleAdd = () => {
        router.push({
          path: "/${config.moduleName}/add",
        });
      };
    `,
    disabled: false,
    type: "primary",
  },
  edit: {
    handlerTemplate: () => `
      /**
       * @description 修改
       * @returns {void}
       */
      const handleEdit = () => {
        router.push({
          path: "/${config.moduleName}/edit",
          query: { id: tableSelected.value[0].id }
        });
      };
    `,
    disabled: "tableSelected.length !== 1",
    type: "primary",
  },
  delete: {
    handlerTemplate: () => `
      /**
       * @description 删除
       * @returns {void}
       */
      const handleDelete = () => {
        const deleteIdArr = [] as number[];
        tableSelected.value.forEach((item) => {
          deleteIdArr.push(item.id as number);
        });

        MdMessageBox.confirm($t('确认删除吗?'), $t('确认'), {
          confirmButtonText: $t('确认'),
          cancelButtonText: $t('取消'),
          type: 'warning',
        })
          .then(() => {
            loading.value = true;
            const ids = deleteIdArr.join(',');
            Api.delete(ids)
              .then((res) => {
                if (res.success) {
                  MdMessage.success($t('删除成功！'));
                  search();
                }
              })
              .finally(() => {
                loading.value = false;
              });
          })
          .catch(() => {
            MdMessage($t('取消删除'));
          });
      };
    `,
    disabled: "tableSelected.length === 0",
    type: "danger",
  },
};

// 首字母大写
const capitalizeFirstLetter = (str) => {
  if (!str) return str;
  return str.charAt(0).toUpperCase() + str.slice(1);
};

// 生成工具栏按钮模板

// :authKey="\`\${route.path.slice(1)}-${key}\`"
const generateToolbarButtons = () => {
  return config.btnPromission
    ?.map((key) => {
      // 导出需要添加权限 但是不需要按钮模版及事件
      if (key.authorityKey === "export") {
        return ``;
      }

      const btnConfig = buttonConfigs[key.authorityKey];
      return `
        <qms-btn
          authKey="${config.moduleName}-${key.authorityKey}"
          type="${btnConfig?.type || "primary"}"
          @click="handle${capitalizeFirstLetter(key.authorityKey)}"
          ${btnConfig?.disabled ? `:disabled="${btnConfig?.disabled}"` : ""}
        >
          {{ $t("${key.authorityName}") }}
        </qms-btn>
      `;
    })
    .join("\n");
};

// 生成处理函数模板
const generateHandlerFunctions = () => {
  return config.btnPromission
    ?.map((key) => {
      // 导出需要添加权限 但是不需要按钮模版及事件
      if (key.authorityKey === "export") {
        return ``;
      }

      const isAssignBtn = buttonConfigs.hasOwnProperty(key.authorityKey);
      if (isAssignBtn) {
        return buttonConfigs[key.authorityKey].handlerTemplate();
      } else {
        return `
              /**
               * @description ${key.authorityName}
               * @returns {void}
               */
              const handle${capitalizeFirstLetter(key.authorityKey)} = () => {};
          `;
      }
    })
    .join("\n\n");
};

module.exports = {
  generateToolbarButtons,
  generateHandlerFunctions,
};
